import axios from 'axios';
import { from } from 'core-js/fn/array';
import { Message } from 'element-ui'
import { URL } from '@/config'
import { reject, resolve } from 'core-js/fn/promise';

const CancelToken = axios.CancelToken;
const source = CancelToken.source()
let pending = []
axios.default.withCredentials = true // 允许跨域携带cookie
axios.default.timeout = 8000 // 设置超时时间8s
axios.default.headers.post['Content-Type'] = 'application/json'
axios.default.headers.post.Accept = 'application/json'
const cancelPending = (config) => {
  pending.forEach((item, index) => {
    if (config) {
      // 重复请求处理
      if (item.UrlPath === config.url) {
        item.Cancel() // 取消请求
        pending.splice(index, 1)
      } else {
        item.Cancel()
        pending.splice(index, 1)
      }
    }
  })
}

/*
* http request请求拦截器
*/

axios.interceptors.request.use(
    config => {
      config.data = JSON.stringify(config.data)
      cancelPending(config)
      config.CancelToken = new CancelToken(res => {
        pending.push({
          UrlPath: config.url,
          Cancel: res
        })
      })
      return config;
    },
    error => {
      // 错误抛到业务代码
        console.log(error);
        return Promise.reject();
    }
);

// http response 响应拦截器
service.interceptors.response.use(
    response => {
        cancelPending(response.config)
        return response
    },
    error => {
      // 错误抛到业务代码
      if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
        error.message = '请求超时，请稍后再试！！！'
        return Promise.reject();
      }
      // 处理http错误，抛到业务代码
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.message = '请求错误(400)'
          break
          case 401:
            error.message = '未授权，请重新登录(401)'
          break
          case 403:
            error.message = '拒绝访问(403)'
          break
          case 404:
            error.message = '请求出错(404)'
          break
          default:
            error.message = `连接错误${err.response.status}`
        }
      } else {
        error.message = '链接服务器失败，请稍后再试！'
      }
      Message.error(error.message)
      return Promise.reject(error)
    }
);

/*
* 封装get方法
* @param url 请求url
* @param params q请求参数
* @return {Promise}
*/
export function get(url, param = {}, timeout) {
  return new Promise((resolve, reject) => {
    let base = URL.PORTAL_BASE_URL
    axios.get(finalUrl, { timeout }).then((res) => {
      const data = res.data
      resolve(data)
    }).catch((error) => {
      reject(error)
    })
  })
}

/*
* 封装post方法
* @param url 请求url
* @param params q请求参数
* @return {Promise}
*/
export function post(url, param = {}, timeout) {
  return new Promise((resolve, reject) => {
    let base = URL.PORTAL_BASE_URL
    axios.post(resUrl, resData, { timeout: paramsTimeout }).then((res) => {
      const data = res.data || {}
      resolve(data)
    }).catch((error) => {
      reject(error)
    }).catch(error => {
      reject(error)
    })
  })
}

// 统一接口处理，返回数据
export default function (args) {
  let url = args.url
  let params = args.params
  let paramsTimeout = +args.timeout || null
  let type = args.type && args.type === 'get' ? 'get' : 'post'
  // 上传文件时传文件流的方法控制
  if (args.type == 'blob') {
    axios.default.headers.post['Content-Type'] = 'application/json;application/octet-stream'
    axios.default.responseType= 'blob'
  } else {
    axios.default.headers.post['Content-Type'] = 'application/json'
     axios.default.responseType= ''

  }
  return new Promise((resolve, reject) => {
    switch (type) {
      case 'get':
        get(url, params, paramsTimeout).then(function(response) {
          resolve(response)
        }).catch(function(error) {
          reject(error)
        })
        break
      case 'post':
        post(args).then(function(response) {
          resolve(response)
        }).catch(function(error) {
          reject(error)
        })
        break
      default:
        break
    }
  })
}